package com.hongshan.wallet.core.comm

import android.app.Application
import android.databinding.ObservableField
import android.os.Bundle
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.core.wallet.BindAccountActivity
import com.hongshan.wallet.core.wallet.RealNameActivity
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.http.HttpResult
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.AutoInject
import com.hongshan.wallet.util.MyActivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import retrofit2.Response

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.comm
 * @author   : zhangxx
 * @date     : 2019/3/29
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class SendSmsViewModel(application: Application) : MyViewModel(application) {

    val colorEnable = application.resources.getColor(R.color.colorPrimary)
    val colorDisable = application.resources.getColor(R.color.gray)

    var bundle: Bundle? = null

    val smsCode = ObservableField("")

    val sendTime = ObservableField("发送")

    val sendStatus = ObservableField(true)

    val sendDesc = ObservableField("验证码发送至手机号: ${MyApplication.user?.mobile}")

    val textColor = ObservableField<Int>(colorEnable)

    @AutoInject(Constant.ROUTE_PARAMS_KEY.PARAM_ACCOUNT_TYPE)
    val account_type:String? = null
//    @AutoInject(Constant.ROUTE_PARAMS_KEY.PARAM_REAL_NAME)
//    val real_name:String? = null
//    @AutoInject(Constant.ROUTE_PARAMS_KEY.PARAM_ID_CARD)
//    val credential_no:String? = null

    val send = View.OnClickListener {
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.sendSms(MyApplication.user!!.mobile).execute() }
            }
            val response = result.await() ?: return@launch
            showSuccess.call()
            if (response.isSuccessful) {
                if (response.body()?.code == 0) {
                    toast("发送成功")
                    sendDesc.set("验证码已发送至手机号: ${MyApplication.user?.mobile}")
                    sendStatus.set(false)
                    textColor.set(colorDisable)
                    for (i in 60 downTo 0) {
                        delay(1000)
                        sendTime.set("已发送 ($i)")
                    }
                    sendStatus.set(true)
                    textColor.set(colorEnable)
                    sendTime.set("重新发送")
                } else {
                    toast(response.body()?.msg)
                }
            }
        }
    }

    val complete = View.OnClickListener {
        val smsCodeStr = smsCode.get()?.trim()
        if (smsCodeStr == null || !Constant.Regex.SMS_VERIFY.toRegex().matches(smsCodeStr)) {
            toast("短信验证码格式不正确")
            return@OnClickListener
        }
        when (bundle?.get(Constant.ROUTE_PARAMS_KEY.SMS_ACTION)) {
            Constant.ROUTE_PARAMS_KEY.ACTION_CHECK_PAY_PWD -> makePwdSend(smsCodeStr)
            Constant.ROUTE_PARAMS_KEY.ACTION_ADD_BANK_CARD -> { addBankCard() }
            Constant.ROUTE_PARAMS_KEY.ACTION_UNBIND_WX_OR_ALIPAY -> {
                unBind()
            }
        }
    }

    fun unBind(){
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.unBind(account_type!!,smsCode.get()!!.trim()).execute() }
            }
            val response = result.await() ?: return@launch
            showSuccess.call()
            if (response.body()?.code == 0) {
                toast("解绑成功")
                MyActivityManager.getActivity(RealNameActivity::class.java)?.finish()
                MyActivityManager.getActivity(BindAccountActivity::class.java)?.run {
                    vm.accountBean?.status = -3
                    vm.initState()
                }
                goto()
            } else {
                toast(response.body()?.msg)
            }
        }
    }

    private fun makePwdSend(smsCodeStr: String) {
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.checkPayPwdCode(smsCodeStr).execute() }
            }
            showSuccess.call()
            val response = result.await() ?: return@launch
            if (response.body()?.code == 0) {
                complete(response)
            } else {
                toast(response.body()?.msg)
            }
        }
    }

    private fun complete(response: Response<HttpResult<Map<String, String>>>) {
        bundle?.putCharSequence(Constant.ROUTE_PARAMS_KEY.PAY_PWD_VERIFY_CODE, response.body()?.data?.get("verify_code"))
        goto()
    }

    fun addBankCard() {
//        GlobalScope.launch(Dispatchers.Main) {
//            val result = GlobalScope.async(Dispatchers.IO) {
//                tryRun {
//                    HttpClient.httpApi.addBankCard(
//                        "3",
//                        verify_code = bundle?.getString(Constant.ROUTE_PARAMS_KEY.PAY_PWD_VERIFY_CODE),
//                        code = smsCode.get()
//                    ).execute()
//                }
//            }
//            val body = result.await()?.body()
//            if (body?.code == 0) {
//                goto()
//            }
//        }
    }

    private fun goto() {
        val path = bundle!![Constant.ROUTE_PARAMS_KEY.SMS_NEXT_URL] as String?
        if (path != null) {
            go(path, bundle)
        }
        if ((bundle?.get(Constant.ROUTE_PARAMS_KEY.SMS_NEED_FINISH) as Boolean?) == true) {
            finish()
        }
    }
}